<template>
  <div class="participation-management">
    <h2>活动参与管理</h2>
    
    <!-- 搜索表单 -->
    <div class="search-form">
      <el-form :inline="true" :model="queryParams" @submit.prevent>
        <el-form-item label="活动">
          <el-select v-model="queryParams.activityId" placeholder="请选择活动" clearable filterable>
            <el-option 
              v-for="activity in activityOptions" 
              :key="activity.id" 
              :label="activity.title"
              :value="activity.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="用户">
          <el-select v-model="queryParams.userId" placeholder="请选择用户" clearable filterable>
            <el-option 
              v-for="user in userOptions" 
              :key="user.id" 
              :label="user.username"
              :value="user.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="签到时间">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD HH:mm:ss"
            :default-time="['00:00:00', '23:59:59']"
          >
          </el-date-picker>
        </el-form-item> -->
        <el-form-item label="投票选项">
          <el-input v-model="queryParams.voteOption" placeholder="请输入投票选项" clearable></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    
    <!-- 操作按钮 -->
    <div class="operation-container">
      <el-button type="primary" @click="handleAdd">添加参与记录</el-button>
    </div>
    
    <!-- 参与记录表格 -->
    <el-table v-loading="loading" :data="participationList" border stripe style="width: 100%">
      <el-table-column prop="id" label="ID" width="60"></el-table-column>
      <el-table-column label="活动信息" width="200">
        <template #default="scope">
          <div>
            <div><b>{{ scope.row.activity ? scope.row.activity.title : '-' }}</b></div>
            <div v-if="scope.row.activity" class="text-small">
              {{ formatDate(scope.row.activity.schedule) }}
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="用户信息" width="150">
        <template #default="scope">
          <div>
            <div>{{ scope.row.user ? scope.row.user.username : '-' }}</div>
            <div v-if="scope.row.user" class="text-small">
              {{ scope.row.user.realName || '-' }}
            </div>
          </div>
        </template>
      </el-table-column>
      <!-- <el-table-column prop="signInTime" label="签到时间" width="180">
        <template #default="scope">
          {{ formatDate(scope.row.signInTime) || '未签到' }}
        </template>
      </el-table-column> -->
      <el-table-column prop="voteOption" label="投票选项" width="120">
        <template #default="scope">
          {{ scope.row.voteOption || '-' }}
        </template>
      </el-table-column>
      <el-table-column prop="feedback" label="活动反馈" show-overflow-tooltip>
        <template #default="scope">
          {{ scope.row.feedback || '-' }}
        </template>
      </el-table-column>
      <el-table-column label="操作" fixed="right" width="150">
        <template #default="scope">
          <!-- 只有管理员和社团负责人可以编辑 -->
          <el-button 
            v-if="canEdit()" 
            link 
            type="primary" 
            @click="handleEdit(scope.row)">编辑</el-button>
          <!-- 管理员、社团负责人可以删除任何记录，学生只能删除自己的记录 -->
          <el-button 
            v-if="canDelete(scope.row)" 
            link 
            type="danger" 
            @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <!-- 分页组件 -->
    <div class="pagination-container">
      <el-pagination
        :current-page="queryParams.page"
        :page-size="queryParams.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getParticipationList, deleteParticipation } from '@/api/activityParticipation'
import { getActivityList } from '@/api/activity'
import { getUserList } from '@/api/user'
import { useUserStore } from '@/store/user'

const router = useRouter()
const userStore = useUserStore()
const loading = ref(false)
const participationList = ref([])
const total = ref(0)
const activityOptions = ref([])
const userOptions = ref([])
const dateRange = ref([])

// 当前用户信息
const currentUser = computed(() => userStore.userInfo)

// 查询参数
const queryParams = reactive({
  page: 1,
  pageSize: 10,
  activityId: null,
  userId: null,
  startTime: null,
  endTime: null,
  voteOption: ''
})

// 判断是否可以编辑参与记录
const canEdit = () => {
  // 只有管理员和社团负责人可以编辑
  return currentUser.value.role === 'admin' 
}

// 判断是否可以删除参与记录
const canDelete = (row) => {
  // 管理员和社团负责人可以删除任何记录，学生只能删除自己的记录
  return currentUser.value.role === 'admin' || 
         (currentUser.value.role === 'club_leader'&& row.user && row.user.id === currentUser.value.id) || 
         (currentUser.value.role === 'student' && row.user && row.user.id === currentUser.value.id)
}

// 监听日期范围变化
watch(dateRange, (newValue) => {
  if (newValue && newValue.length === 2) {
    queryParams.startTime = newValue[0]
    queryParams.endTime = newValue[1]
  } else {
    queryParams.startTime = null
    queryParams.endTime = null
  }
})

// 获取参与记录列表
const getList = async () => {
  loading.value = true
  try {
    // 如果是学生角色，只查询自己的参与记录
    if (currentUser.value.role === 'student') {
      queryParams.userId = currentUser.value.id
    }
    
    const res = await getParticipationList(queryParams)
    if (res.data && res.code === 200) {
      participationList.value = res.data.list || []
      total.value = res.data.total || 0
    } else {
      ElMessage.error(res.message || '获取参与记录列表失败')
    }
  } catch (error) {
    console.error('获取参与记录列表出错:', error)
    ElMessage.error('获取参与记录列表失败')
  } finally {
    loading.value = false
  }
}

// 加载活动列表
const loadActivities = async () => {
  try {
    const res = await getActivityList({ pageSize: 1000 })
    if (res.data && res.code === 200) {
      activityOptions.value = res.data.list || []
    } else {
      ElMessage.error(res.message || '获取活动列表失败')
    }
  } catch (error) {
    console.error('获取活动列表出错:', error)
    ElMessage.error('获取活动列表失败')
  }
}

// 加载用户列表
const loadUsers = async () => {
  try {
    const res = await getUserList({ pageSize: 1000 })
    if (res.data && res.code === 200) {
      userOptions.value = res.data.list || []
    } else {
      ElMessage.error(res.message || '获取用户列表失败')
    }
  } catch (error) {
    console.error('获取用户列表出错:', error)
    ElMessage.error('获取用户列表失败')
  }
}

// 搜索
const handleSearch = () => {
  queryParams.page = 1
  getList()
}

// 重置
const handleReset = () => {
  queryParams.activityId = null
  
  // 学生只能查看自己的记录，重置时不清空userId，管理员和社团负责人可以查看所有
  if (currentUser.value.role === 'admin' || currentUser.value.role === 'club_leader') {
    queryParams.userId = null
  } else {
    queryParams.userId = currentUser.value.id
  }
  
  dateRange.value = []
  queryParams.startTime = null
  queryParams.endTime = null
  queryParams.voteOption = ''
  queryParams.page = 1
  getList()
}

// 添加参与记录
const handleAdd = () => {
  router.push('/activity-participations/add')
}

// 编辑参与记录
const handleEdit = (row) => {
  router.push(`/activity-participations/edit/${row.id}`)
}

// 删除参与记录
const handleDelete = (row) => {
  ElMessageBox.confirm(
    '确定要删除该活动参与记录吗？',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      const res = await deleteParticipation(row.id)
      if (res.code === 200) {
        ElMessage.success('删除成功')
        getList()
      } else {
        ElMessage.error(res.message || '删除失败')
      }
    } catch (error) {
      console.error('删除参与记录出错:', error)
      ElMessage.error('删除失败')
    }
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

// 处理每页条数变化
const handleSizeChange = (size) => {
  queryParams.pageSize = size
  getList()
}

// 处理页码变化
const handleCurrentChange = (page) => {
  queryParams.page = page
  getList()
}

// 日期格式化
const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 初始化
onMounted(() => {
  loadActivities()
  loadUsers()
  getList()
})
</script>

<style scoped>
.participation-management {
  padding: 20px;
}

.search-form {
  background-color: #f5f7fa;
  padding: 18px;
  border-radius: 4px;
  margin-bottom: 20px;
}

.operation-container {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.text-small {
  font-size: 12px;
  color: #909399;
}
</style> 